<template>
  <div class="container" >

    <el-form :inline="true" ref="formRef" :model="form" :rules="formRules">
       <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" style="width: 500px"></el-input>
      </el-form-item>
      <el-form-item label="分类" class="category">
        <el-select v-model="form.categoryId" 
          placeholder="请选择"
          filterable
          
          default-first-option
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      

      <el-form-item label="标签" class="tags">
        <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            @change="handleChange"
            placeholder="请选择文章标签">
            <el-option
              v-for="item in tags"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
      </el-form-item> 

      <el-form-item >
        <el-button type="primary" @click="showAddImgDialog">添加封面图片</el-button>
      </el-form-item>

    </el-form>


    <el-dialog
      class="addDialog"
      title="添加缩略图"
      :visible.sync="addImgdialogVisible"
      width="30%"
      :before-close="handleCloseDialog">
      
      <!-- <el-form-item label="上传图片"> -->
      <el-upload
        class="avatar-uploader"
        action="/api/upload"
        :auto-upload="true"
        name="file"
        :show-file-list="false"
        :on-success="handleAddSuccess"
        :before-upload="beforeImageUpload">
        <img v-show="imageUrl" :src="imageUrl" class="thumbnail">
        <i v-show="!imageUrl" class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    <!-- </el-form-item> -->
    <span class="upload-tip">点击上传或更换图片</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelImgDialog">取 消</el-button>
        <el-button type="primary" @click="confirmImg">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 富文本编辑器 -->
      <div class="editor">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 350px; overflow-y: hidden;"
            v-model="form.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
      </div>
      <el-button type="primary" style="margin-top: 10px; float: right" @click="submit">提交</el-button>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import hljs from 'highlight.js'
// import 'highlight.js/styles/monokai-sublime.css'
export default {
  components: {
    Editor,
    Toolbar
  },
  data() {
    return {
      tagVisible: false,
      addImgdialogVisible: false,
      imageUrl: '',
      img: '',
      tagValue: '',
      tags: [],
      form: {
        id: '',
        title: '',
        categoryId: '',
        tags: [],
        tagsNew: [],
        content: '',
        img: ''
      },
      formRules: {
        title: { required: true, message: "请输入标题", trigger: "blur" },
      },
      categories: [
        {id: 1, label: '分类1'},
        {id: 2, label: '分类2'},
        {id: 3, label: '分类3'},
        {id: 4, label: '分类4'},
        {id: 5, label: '分类5'},
      ],
      editor: null,
      uploadConfig: null,
      toolbarConfig: { },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
    };
  },
  methods: {
    onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        // this.editor.highlight = hljs
        this.uploadConfig = this.editor.getMenuConfig('uploadImage')
        this.uploadConfig.server =  '/api/upload'
        this.uploadConfig.customInsert = (res, insertFn) => {                  // JS 语法
              // res 即服务端的返回结果
              if (!res.status) {
                this.$message.error(res.message)
              }

              const url = `/api/download/${res.data}`
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(url, url, url)
          }
        this.uploadConfig.fieldName =  'file'
        this.uploadConfig.onProgress = (progress) => {       // JS 语法
              // progress 是 0-100 的数字
              console.log('progress', progress)
        }
        // this.codeSelectLang = {
        //     // 代码语言
        //     codeLangs: [
        //         { text: 'CSS', value: 'css' },
        //         { text: 'HTML', value: 'html' },
        //         { text: 'XML', value: 'xml' },
        //         { text: 'C', value: 'c' },
        //         { text: 'Java', value: 'java' },
        //         { text: 'JavaScript', value: 'js' },
        //         // 其他
        //     ]
        // }
        // console.log(this.uploadConfig);
    },
    handleClose(tag) {
      this.form.tags.splice(this.form.tags.indexOf(tag), 1);

    },
    // 处理添加图片的弹框
    handleCloseDialog() {
      this.addImgdialogVisible = false
    },
    showAddImgDialog() {
      this.addImgdialogVisible = true
    },

    // 取消添加图片
    cancelImgDialog() {
      console.log('cancel');
      this.addImgdialogVisible = false
      this.imageUrl = `/api/download/${this.form.img}`
    },
    showInput() {
      this.tagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      })
    },
    // 标签去重
    handleInputConfirm() {
      let set = new Set(this.form.tags)
      let tagValue = this.tagValue;
      if (tagValue) {
        set.add(tagValue)
        this.form.tags = [...set.values()];
      }
      this.tagVisible = false;
      this.tagValue = '';
    },

    handleChange(val){
      // const index = []
      this.form.tagsNew = val.filter(item => typeof item === 'string')
      // this.form.tags = this.form.tags.filter(item => typeof item === 'number')
      console.log(val, this.form.tagsNew);
    },
      // 获取分类
    getCategories() {
      this.$http.get('/category')
      .then(res => {
        res = res.data
        if (!res.status) {
          return this.$message.error(res.message)
        }
        this.categories = res.data;
      })
    },
    getTags() {
      this.$http.get('/tag')
      .then(res => {
        res = res.data
        if (!res.status) {
          return this.$message.error(res.message)
        }
        this.tags = res.data;
      })
    },
    // 提交文章
    async submit() {
      console.log(this.$refs.formRef);
      this.form.tags = this.form.tags.filter(item => typeof item === 'number')
      const flag = await this.$refs.formRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return
        console.log(this.form.id);
        let method = this.form.id ? 'PUT':'POST'
        console.log(method);
        this.$http({
          url: '/article',
          method: method,
          data: this.form
        })
        // this.$http.post('/article', this.form)
        .then(res => {
          res = res.data
          if (!res.status) {
            return this.$message.error(res.message)
          }
          this.$message.success(res.message)
          this.form = {}
          // this.$refs.formRef.resetFields()
          this.form.content = ''
          this.$router.push('/admin/articleList')
          // this.html = ''
        })
      })

      console.log('flag = ' + flag);

      // this.form.body = this.html
      
    },

    handleAddSuccess(res, file, fileList) {
      this.img = res.data
      this.imageUrl = `/api/download/${res.data}`
      this.$message.success(res.message)
    },

    beforeImageUpload(file) {
      console.log(file);
      const isImage = ((type) => {
        return type.split('/')[0] === 'image'
      })(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
      this.$message.error('上传图片只能是Image编码相关格式!');
      }
      if (!isLt2M) {
      this.$message.error('上传套餐图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    confirmImg() {
      this.form.img = this.img
      this.addImgdialogVisible = false
    },

    getArticle(id) {
      const that = this
      this.$http.get(`/article/${id}`)
      .then(res => {
        res = res.data
        if (res.status) {
          this.form = res.data
          // this.imgaeUrl = res.data.img
          if (res.data.img) {
            this.imageUrl = `/api/download/${res.data.img}`
          }
          // this.setImg(res.data.img)
        }
      })
    }

  },

  // 监听,当路由发生变化的时候执行
  watch:{
    $route(to){
      if (to.path === '/article') {
        this.form = {}
      }
    }
  },

  mounted() {
    this.getCategories()
    this.getTags()
    // console.log(this.$route.params.id)
    // 修改文章前查询对应的数据
    const id = this.$route.params.id
    // console.log(id);
    if (id) {
      this.getArticle(id)
    }
  },
  beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
  }
};
</script>

<style scoped>
.tags .el-select {
  width: 500px;
}
.editor {
  border: 1px solid #ccc
}

.addDialog {
  min-width: 350px;
}

.thumbnail {
  width: 100%;
  max-height: 350px;
}

.upload-tip {
  padding: 10px 5px 5px 5px;
  font-size: 1.2rem;
  text-align: center;
  display: block;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

/* .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .tags {
    display: block;
  } */
  .container {
    padding: 20px 0;
  }
</style>>

<style src="@wangeditor/editor/dist/css/style.css"></style>